package com.example.controller;

import com.example.biz.IUserBiz;
import com.example.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author:帅帅的刘
 * @Description:
 * @Date:Create In 2019-09-16 14:28
 **/
@Controller
public class UserController {

    @Autowired
    private IUserBiz biz;


    @RequestMapping({"/", "login"})
    public String index() {
        return "login";
    }

    @RequestMapping("main")
    public String main() {
        return "main";
    }

    @RequestMapping("/regist")
    public String regist() {
        return "saveuser";
    }






    @PostMapping("/loginUser")
    public String loginUser(User user) {

        // 获取Subject主体
        Subject loginuser = SecurityUtils.getSubject();
        // 判断时候存在登录的信息
        if (!loginuser.isAuthenticated()) {
            // 如果没有登录则获取令牌并将登录信息存入UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassWord());

            try {
                // 执行认证操作
                loginuser.login(token);
            } catch (Exception e) {
                System.out.println(e.getMessage());

                return "login";

            }

        }
        return "main";
    }


    /**
     * 注册用户  使用MD5 加密
     */

    @PostMapping("user")
    public String registUser(User user) {
        // 获取加密工具
        ByteSource password = ByteSource.Util.bytes(user.getPassWord());
        // 使用SimpleHash 加密
        Object newPassword = new SimpleHash("md5", password, user.getUserName(), 1024);
        user.setPassWord(newPassword.toString());
        biz.saveUser(user);
        return "main";
    }


}
